#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2019/2/23 16:54
@desc
"""

import psycopg2
from DBUtils.PooledDB import PooledDB

from bratislava.conf.settings import postgresInfo


class OPPostgre(object):

    __pool = None

    def __init__(self):
        # 构造函数，创建数据库连接、游标
        self.coon = OPPostgre.get_conn()
        self.cur = self.coon.cursor()


    # 数据库连接池连接
    @staticmethod
    def get_conn():
        if OPPostgre.__pool is None:
            try:
                __pool = PooledDB(creator=psycopg2, mincached=1, maxcached=20, host=postgresInfo['host'], user=postgresInfo['user'], password=postgresInfo['passwd'], dbname=postgresInfo['db'], port=postgresInfo['port'])
                print(__pool)
            except Exception as e:
                print(e)
        return __pool.connection()

    # 插入\更新\删除sql
    def op_insert(self, sql):
        print('op_insert', sql)
        insert_num = self.cur.execute(sql)
        print('mysql sucess ', insert_num)
        self.coon.commit()
        return insert_num

    # 查询
    def op_select(self, sql):
        print('op_select', sql)
        self.cur.execute(sql)  # 执行sql
        select_res = self.cur.fetchone()  # 返回结果为字典
        print('op_select', select_res)
        return select_res

    #释放资源
    def dispose(self):
        self.coon.close()
        self.cur.close()
